/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Simple servlet that decodes a URl generated by the NFC Smart Tag.
 * Assumes the station key is 00..00 (16 bytes)
 */

package com.appspot.nfcsmarttag;

import com.appspot.nfcsmarttag.url.InvalidInputException;
import com.appspot.nfcsmarttag.url.SimpleKeyStore;
import com.appspot.nfcsmarttag.url.SmartTagKeyStoreInterface;
import com.appspot.nfcsmarttag.url.Url4Tag;

import java.io.IOException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class NfcSmartTagServlet extends HttpServlet {
  
  private static final String PAGE_HEADER =
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
      + "<html><head>"
      + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"
      + "<title>NFC Smart Tag Test Server</title>"
      + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.4, user-scalable=yes\">"
      + "</head><body>";

  private static final String PAGE_FOOTER = "</body></html>";
  
  SmartTagKeyStoreInterface keyStore;
  
  public NfcSmartTagServlet() {
    keyStore = new SimpleKeyStore();  
  }
  
  private static String hexString(byte[] byteArray) {
    StringBuilder stringBuilder = new StringBuilder();
    for (byte b : byteArray) {
      stringBuilder.append(String.format("%02x", b));
    }
    return stringBuilder.toString();
  }
    
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    String nv = req.getParameter("nv");
    resp.getWriter().println(PAGE_HEADER);
    
    if (nv != null && !nv.isEmpty()) {
      Url4Tag url4tag;
      try {
        url4tag = Url4Tag.fromEncodedValue(keyStore, nv);
        resp.getWriter().println("<pre>");
        resp.getWriter().println("Tag Id:" + hexString(url4tag.getTagId()));
        resp.getWriter().println("SmartTagInfo:\n" + url4tag.getNfcSmartTagInfo());
        resp.getWriter().println("</pre>");
      } catch (InvalidInputException e) {
        resp.getWriter().println("Decoding error");          
      }
    } else {
      resp.getWriter().println("nv parameter is missing");
    }          
    resp.getWriter().println(PAGE_FOOTER);
  }
}
